package com.sugar.config;

import com.sugar.factory.ThreadPoolFactory;
import com.sugar.monitor.ThreadPoolMonitor;
import com.sugar.properties.ThreadPoolProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ExecutorService;

@Configuration
@EnableConfigurationProperties(ThreadPoolProperties.class)
public class ThreadPoolAutoConfiguration {

    /**
     * 业务线程池 Bean
     */
    @Bean(name = "businessTaskExecutor")
    @ConditionalOnMissingBean(name = "businessTaskExecutor")
    public ExecutorService businessTaskExecutor(ThreadPoolProperties properties) {
        return ThreadPoolFactory.build(properties);
    }

    /**
     * 线程池监控 Bean，只有开启监控配置时生效
     */
    @Bean
    //条件注解：只有当配置文件（如application.yml）中存在app.threadpool.monitor-enabled属性且值为true时，该Bean才会被创建和注册。
    @ConditionalOnProperty(prefix = "app.threadpool", name = "monitor-enabled", havingValue = "true")
    //条件注解：如果Spring容器中已经存在类型为ThreadPoolMonitor的Bean，则当前方法不会被执行，不会重复注册同类型Bean。
    @ConditionalOnMissingBean(ThreadPoolMonitor.class)
    public ThreadPoolMonitor businessTaskExecutorMonitor(
            ThreadPoolProperties properties,
            @Autowired @Qualifier("businessTaskExecutor") ExecutorService executor) {
        return new ThreadPoolMonitor(
                "businessTaskExecutor",
                executor,
                properties.getMonitorIntervalSeconds()
        );
    }
}
